<script setup lang="ts">
let loading = ref(true)
import C2Scroll from './c2-scroll'
import C3Scroll from './c3-scroll'
import ItemsContainer from './items-container'
import { onShow, onLoad, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
import { toRaw } from 'vue';
import _ from 'lodash'

import {
  getC2ListByC1Id,
  getC3ListByC1IdAndC2Id,
  pageGood
} from '../../api/search'
import { ref, reactive, nextTick } from 'vue'

enum selectionMode {
  x,
  y
}

let queryWrapper = reactive({
  c1Id: undefined,
  c2Id: undefined,
  c3Id: undefined,
  c2SecondName: undefined,
  c3SecondName: undefined,
  pageSize: 10,
  pageNumber: 1,
  keyword: ''
})
const c2List = ref([])
const c3List = ref([])
const goodList = ref([])
const totalPage = ref(0)
const selectionModeRef = ref(undefined)
onShareAppMessage(() => {
  const ps = _.cloneDeep(getCurrentPages())
  const p = ps.pop()
  const { $page } = p
  let path = $page.fullPath;
  const title:string[]= []
  if ($page.fullPath && $page.fullPath.includes('?')) {
    const url = $page.fullPath.split('?')
    const url0 = url[0]
    const q = toRaw(queryWrapper)
    const o = Object.keys(q).map(key => `${key}=${q[key] ? q[key] : ''}`)

    Object.keys(q).forEach(key => {
      if (key == 'c1Id' || key == 'c2SecondName' || key == 'c3SecondName') {
        title.push(q[key])
      }
    })
    o.push('showHomeBtn=1')
    path = [url0, o.join('&')].join('?')

  }
  return {
    title: title.length > 0 ? title.join('#') : '会一美装板',
    path
  }
})

onShareAppMessage(() => {
  const ps = _.cloneDeep(getCurrentPages())
  const p = ps.pop()
  const { $page } = p
  let path = $page.fullPath;
  const title:string[] = []
  if ($page.fullPath && $page.fullPath.includes('?')) {
    const url = $page.fullPath.split('?')
    const url0 = url[0]
    const q = toRaw(queryWrapper)
    const o = Object.keys(q).map(key => `${key}=${q[key] ? q[key] : ''}`)

    Object.keys(q).forEach(key => {
      if (key == 'c1Id' || key == 'c2SecondName' || key == 'c3SecondName') {
        q[key] && title.push(q[key])
      }
    })
    o.push('showHomeBtn=1')
    path = [url0, o.join('&')].join('?')

  }
  return {
    title: title.length > 0 ? title.join('#') : '会一美装板',
    path
  }
})

onLoad((options) => {
  queryWrapper.c1Id = options.c1Id
  queryWrapper.pageNumber = options.pageNumber ? options.pageNumber : 1
  queryWrapper.pageSize = options.pageSize ? options.pageSize : 10
  queryWrapper.keyword = options.keyword ? options.keyword : ''
  queryWrapper.c2SecondName = options.c2SecondName 
  queryWrapper.c3SecondName = options.c3SecondName
  if (queryWrapper.c1Id) {
    init().then(() => {
      if (options.c2Id) {
        queryWrapper.c3Id = options.c3Id
        queryWrapper.c2Id = options.c2Id
        refreshData()
      }

    })
  }



})
onShow(() => {
  loading === true && init()
})

const init = () => {
  loading.value = true
  return getC2ListByC1Id(queryWrapper.c1Id, queryWrapper.c3Id, queryWrapper.keyword)
    .then((r) => {
      c2List.value = r
      //do not update the c1Id
      return getC3ListByC1IdAndC2Id(
        queryWrapper.c1Id,
        '',
        queryWrapper.keyword
      )
    })
    .then((r) => {
      c3List.value = r
      status.value = 'loading'
      return pageGood(queryWrapper)
    })
    .then((r) => {
      goodList.value = r.items
      totalPage.value = r.pageInfo.totalPage
      if (r.pageInfo.totalPage == r.pageInfo.currentPage) {
        status.value = 'nomore'
      }
      return {}
    })
    .catch((e) => {
      console.error(e)
      status.value = 'loadmore'
    })
    .finally(() => {
      nextTick(() => {
        loading.value = false
      })
    })
}

const chooseSelectionMode = (mode: selectionMode) => {
  if (selectionModeRef.value === undefined) {
    selectionModeRef.value = mode
  }
}

const currentSelectionModeEqX = () => selectionModeRef.value == selectionMode.x
const currentSelectionModeEqY = () => selectionModeRef.value == selectionMode.y

const handleC2Tap = async (c2) => {
  if (loading.value) {
    return
  }

  const c2Id = c2.id
  chooseSelectionMode(selectionMode.y)
  if (currentSelectionModeEqY()) {
    queryWrapper.c3Id = undefined
    queryWrapper.c3SecondName = undefined
    let r = await getC3ListByC1IdAndC2Id(
      queryWrapper.c1Id,
      c2Id,
      queryWrapper.keyword
    ),
      rid = r.map((el: any) => {
        return el.id
      })
    c3List.value = c3List.value.map((el: any) => {
      el.exist = rid.includes(el.id)
      return el
    })
  }

  loading.value = true
  // 一些初始化的操作
  goodList.value = []
  totalPage.value = 0
  queryWrapper.c2Id = c2Id
  queryWrapper.c2SecondName = c2.name
  queryWrapper.pageNumber = 1
  status.value = 'loading'
  try {
    let { pageInfo, items } = await pageGood(queryWrapper)
    goodList.value = items
    totalPage.value = pageInfo.totalPage
    if (queryWrapper.pageNumber >= totalPage.value) {
      status.value = 'nomore'
    }
  } catch (e) {
    console.error(e)
  } finally {
    nextTick(() => {
      loading.value = false
    })

  }
}

const handleC3Tap = async (c3) => {
  if (loading.value) {
    return
  }
  const c3Id = c3.id
  chooseSelectionMode(selectionMode.x)
  if (currentSelectionModeEqX()) {
    queryWrapper.c2Id = undefined
    queryWrapper.c2SecondName = undefined
    let r = await getC2ListByC1Id(
      queryWrapper.c1Id,
      c3Id,
      queryWrapper.keyword
    ),
      rid = r.map((el: any) => {
        return el.id
      })
    let s = c2List.value.map((el: any) => {
      el.exist = rid.includes(el.id) ? 1 : 0
      return el
    })
    c2List.value = s
  }
  loading.value = true
  goodList.value = []
  totalPage.value = 0
  queryWrapper.c3Id = c3Id
  queryWrapper.c3SecondName = c3.name
  queryWrapper.pageNumber = 1
  //reload c2 List,
  status.value = 'loading'

  try {
    let { pageInfo, items } = await pageGood(queryWrapper)

    goodList.value = items
    totalPage.value = pageInfo.totalPage
    if (queryWrapper.pageNumber >= totalPage.value) {
      status.value = 'nomore'
    }

  } catch (e) {
    console.error(e)
  } finally {
    nextTick(() => {
      loading.value = false
    })
  }



}

let status = ref('loadmore')

const handleOnLower = async () => {
  if (queryWrapper.pageNumber >= totalPage.value) {
    return
  }

  if (loading.value) {
    return
  }
  status.value = 'loading'

  loading.value = true
  queryWrapper.pageNumber++
  let { pageInfo, items } = await pageGood(queryWrapper)
  goodList.value = goodList.value.concat(items)
  totalPage.value = pageInfo.totalPage
  if (queryWrapper.pageNumber >= totalPage.value) {
    status.value = 'nomore'
  }
  nextTick(() => {
    loading.value = false
  })
}

const refreshData = async () => {
  if (loading.value) {
    return
  }

  chooseSelectionMode(selectionMode.y)

  if (currentSelectionModeEqY()) {
    let r = await getC3ListByC1IdAndC2Id(
      queryWrapper.c1Id,
      queryWrapper.c2Id,
      queryWrapper.keyword
    ),
      rid = r.map((el: any) => {
        return el.id
      })
    c3List.value = c3List.value.map((el: any) => {
      el.exist = rid.includes(el.id)
      return el
    })
  }
  status.value = 'loading'

  loading.value = true

  let { pageInfo, items } = await pageGood(queryWrapper)
  goodList.value = items
  totalPage.value = pageInfo.totalPage
  if (queryWrapper.pageNumber >= totalPage.value) {
    status.value = 'nomore'
  }
  nextTick(() => {
    loading.value = false
  })
}

const handleSearch = async () => {
  if (loading.value) {
    return
  }
  chooseSelectionMode(selectionMode.y)
  loading.value = true
  queryWrapper.pageNumber = 1
  let { pageInfo, items } = await pageGood(queryWrapper)
  goodList.value = items
  totalPage.value = pageInfo.totalPage
  if (queryWrapper.pageNumber >= totalPage.value) {
    status.value = 'nomore'
  }
  nextTick(() => {
    loading.value = false
  })
}
</script>

<template>
  <view class="flex-container">
    <ForOneHeader :enableBack="true" />
    <view class="search-container">
      <view class="input-container">
        <u-search height="70rpx" :showAction="false" :clearabled="true" placeholder="请输入产品名称/型号"
          v-model="queryWrapper.keyword" @search="handleSearch"></u-search>
      </view>
      <view class="mid-row">
        <C2Scroll class="c2-scroll" :c2List="c2List" :c2Id="queryWrapper.c2Id" @do="handleC2Tap" />
        <view class="right">
          <C3Scroll class="c3-scroll" :c3List="c3List" :c3Id="queryWrapper.c3Id" @do="handleC3Tap" />
          <ItemsContainer :status="status" @on-lower="handleOnLower" class="items-container" :itemList="goodList" />
        </view>
      </view>
    </view>
    <!--    <u-loading-page :loading="loading"></u-loading-page>-->
  </view>
</template>

<style lang="scss" scoped>
.flex-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

// $container-height: cala(100vh - )

.search-container {
  flex: 1;
  overflow: hidden;
  // height: 100vh;
  display: flex;
  flex-direction: column;

  .input-container {
    padding: 10rpx;
    box-shadow: 0 0 10rpx #333;
    margin-bottom: 15rpx;
  }

  .mid-row {
    flex: 1;
    display: flex;
    overflow: hidden;

    .c2-scroll {
      //width: 150rpx;
    }

    .right {
      flex: 1;
      overflow: hidden;
      display: flex;
      flex-direction: column;

      .items-container {
        flex: 1;
        overflow: hidden;
      }
    }
  }
}

.mid-c2-scroll {
  width: 180rpx;
}
</style>
